package com.example.demo.controller;


import com.example.demo.Server.Look_for_jobServer;
import com.example.demo.entity.DeliveryRecord;
import com.example.demo.entity.JobPosition;
import com.example.demo.result.PageResult;
import com.example.demo.result.Result;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class Look_for_job_Controller {
    @Autowired
    private Look_for_jobServer look_for_jobServer;



    @PostMapping("/select_job")
    public Result<ArrayList> Look_for_jon() {



        ArrayList<JobPosition> jobPositions = look_for_jobServer.select_Look_for_jon();

        return Result.success(jobPositions);
    }
    @PostMapping("/add_job")
    public Result<Integer> add_job(@RequestBody  JobPosition jobPosition) {
        int result = look_for_jobServer.add_job(jobPosition);
        return Result.success(result);
    }
    @DeleteMapping("/delete_job")
    public Result<Integer> delete_job( Integer id) {
        int result = look_for_jobServer.delete_job(id);
        return Result.success(result);
    }
    @PostMapping("/update_job")
    public Result<Integer> update_job(@RequestBody JobPosition jobPosition) {
        int result = look_for_jobServer.update_job(jobPosition);
        return Result.success(result);
    }
    @GetMapping("/select_job_page")
    public Result<PageResult> select_job_page(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer hrId,
            JobPosition jobPosition) {

        // 安全处理 hrId
        int safeHrId = hrId == null ? 0 : hrId;

        // 调用 Service 查询分页数据
        PageResult pageResult = look_for_jobServer.select_Look_for_jon_page(page, size, safeHrId, jobPosition);

        return Result.success(pageResult);
    }

    @PostMapping("/add_hope_job")
    public Result<Integer> add_hope_job(@RequestBody  JobPosition jobPosition) {


        return Result.success();
    }

    /**
     * 投递简历接口
     */

    @PostMapping("/api/deliver_resume")
    public Map<String, Object> deliverResume(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取参数
            Integer userId = (Integer) params.get("userId");
            Integer jobId = (Integer) params.get("jobId");
            Integer hrId = (Integer) params.get("hrId");
            String resumePath = (String) params.get("resumePath");

            // 参数校验
            if (userId == null || jobId == null || hrId == null || resumePath == null || resumePath.isEmpty()) {
                result.put("code", 0);
                result.put("msg", "参数不完整");
                return result;
            }

            // 执行投递操作
            boolean success = look_for_jobServer.deliverResume(userId, jobId, hrId, resumePath);

            if (success) {
                result.put("code", 1);
                result.put("msg", "简历投递成功");
            } else {
                result.put("code", 0);
                result.put("msg", "该岗位已投递过");
            }
        } catch (Exception e) {
            result.put("code", 0);
            result.put("msg", "投递失败: " + e.getMessage());
        }

        return result;
    }




    /**
     * 获取用户投递的岗位ID列表
     */
    @PostMapping("/api/get_delivery_records")
    public ResponseEntity<Map<String, Object>> getDeliveryRecords(@RequestBody Map<String, Object> payload) {
        Map<String, Object> response = new HashMap<>();

        try {
            Integer userId = ((Number) payload.get("userId")).intValue();
            if (userId == null) {
                response.put("code", 0);
                response.put("msg", "用户ID不能为空");
                return ResponseEntity.ok(response);
            }

            List<Integer> jobIds = look_for_jobServer.getDeliveryJobIdsByUserId(userId);

            response.put("code", 1);
            response.put("data", jobIds);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("code", 0);
            response.put("msg", "获取投递记录失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 根据岗位ID列表获取岗位详情
     */
    @PostMapping("/api/get_delivered_jobs")
    public ResponseEntity<Map<String, Object>> getDeliveredJobs(@RequestBody Map<String, Object> payload) {
        Map<String, Object> response = new HashMap<>();

        try {
            List<Integer> jobIds = new ArrayList<>();
            Object jobIdsObj = payload.get("jobIds");

            if (jobIdsObj instanceof List) {
                for (Object obj : (List<?>) jobIdsObj) {
                    if (obj instanceof Number) {
                        jobIds.add(((Number) obj).intValue());
                    }
                }
            }

            // 如果jobIds为空或null，返回空列表
            if (jobIds.isEmpty()) {
                response.put("code", 1);
                response.put("data", new ArrayList<>());
                return ResponseEntity.ok(response);
            }

            List<JobPosition> jobs = look_for_jobServer.getDeliveredJobsByUser(
                    ((List<Integer>) jobIds).get(0) != null ?
                            Integer.valueOf(payload.get("userId").toString()) :
                            null
            );

            // 重新实现获取指定jobIds的岗位信息
            List<JobPosition> specificJobs = new ArrayList<>();
            List<JobPosition> allDeliveredJobs = look_for_jobServer.getDeliveredJobsByUser(
                    Integer.valueOf(payload.get("userId").toString())
            );

            Set<Integer> jobIdSet = new HashSet<>(jobIds);
            for (JobPosition job : allDeliveredJobs) {
                if (jobIdSet.contains(job.getJobId())) {
                    specificJobs.add(job);
                }
            }

            response.put("code", 1);
            response.put("data", specificJobs);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", 0);
            response.put("msg", "获取岗位详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 更简单直接的方法：根据用户ID获取已投递岗位详情
     */
    @PostMapping("/api/get_delivered_jobs_by_user")
    public ResponseEntity<Map<String, Object>> getDeliveredJobsByUser(@RequestBody Map<String, Object> payload) {
        Map<String, Object> response = new HashMap<>();

        try {
            Integer userId = ((Number) payload.get("userId")).intValue();

            if (userId == null) {
                response.put("code", 0);
                response.put("msg", "用户ID不能为空");
                return ResponseEntity.ok(response);
            }

            List<JobPosition> jobs = look_for_jobServer.getDeliveredJobsByUser(userId);

            // 添加投递时间信息（如果有需要）
            List<Map<String, Object>> result = new ArrayList<>();
            List<DeliveryRecord> records = look_for_jobServer.getDeliveryRecordsWithDetailsByUserId(userId);

            Map<Integer, DeliveryRecord> recordMap = new HashMap<>();
            for (DeliveryRecord record : records) {
                recordMap.put(record.getJobId(), record);
            }

            for (JobPosition job : jobs) {
                Map<String, Object> jobWithTime = new HashMap<>();
                jobWithTime.put("jobId", job.getJobId());
                jobWithTime.put("name", job.getName());
                jobWithTime.put("salary", job.getSalary());
                jobWithTime.put("location", job.getLocation());
                jobWithTime.put("experience", job.getExperience());
                jobWithTime.put("education", job.getEducation());
                jobWithTime.put("hrId", job.getHrId());

                DeliveryRecord record = recordMap.get(job.getJobId());
                if (record != null) {
                    jobWithTime.put("deliverTime", record.getDeliverTime());
                    jobWithTime.put("hrName", ""); // 如果需要HR姓名，需要关联HR表
                }

                result.add(jobWithTime);
            }

            response.put("code", 1);
            response.put("data", result);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", 0);
            response.put("msg", "获取岗位详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }




}
